import os
import time

# Create your views here.
from django.db.models import Q, Case, When, IntegerField

#django模型
from bid.generate.models import ExTeamProject, ExTeamWork,ExTeamQualification, ExTeam

from zentao.settings import BIG_SAVE_FOLDER, ROOT_FOLDER

#对话生成
from bid.generate.tools.generate_team import generate_team

#团队信息获取
def get_team(_type, ids, bid_id, headerid=0, extra={}):
    # 格式化
    team_info = {}

    # 查询相关人员
    query = Q(id__in=ids)

    # 创建一个Case表达式用于排序
    preserved_order = Case(
        *[When(id=id, then=pos) for pos, id in enumerate(ids)],
        output_field=IntegerField()
    )

    team = ExTeam.objects.filter(query).select_related('degreeFile').all().distinct().order_by(preserved_order)

    # 所有用户
    accounts = set()

    # id对应account
    degree_id2account = {}
    id2position = extra['id2position']

    for i, account in enumerate(team, start=1):

        accounts.add(account.account)
        degree_id2account[account.id] = account.account

        if account.workYears:
            if account.id == headerid:
                workYears = f'{account.workYears}年以上项目管理经验'
            else:
                workYears = f'{account.workYears}年以上'
        else:
            workYears = '未录入工作经验'
        # workYears = f'{account.workYears}年以上'

        # 获取学位证书
        file = account.degreeFile
        if file:
            degreeFile = [os.path.join(ROOT_FOLDER, file.path)]
        else:
            degreeFile = []

        if str(account.id) == str(headerid):
            position = '项目负责人'
        else:
            position = id2position[str(account.id)]

        # 用户信息
        team_info[account.account] = {
            "职责分工": position,
            "行政办公项目年限（年）": workYears,
            "主要持有证书": [],
            "姓名": account.name,
            "学历": account.degree,
            "本项目中职务": position,
            "主要资格证书名称及编号": [],
            "主要工作经历": [],
            "以往参与项目情况": [],
            "学历截图": degreeFile,
            "证书截图": []
        }

    # 团队证书
    # id对应account
    qua_id2account = {}
    query = Q(account__in=accounts)

    quas = ExTeamQualification.objects.filter(query).values('id', 'account', 'name', 'number', 'level',
                                                            'file__path').distinct()

    for qua in quas:
        if qua['level']:
            team_info[qua['account']]['主要持有证书'].append(f"{qua['name']}({qua['level']})")
        else:
            team_info[qua['account']]['主要持有证书'].append(f"{qua['name']}")
        team_info[qua['account']]['主要资格证书名称及编号'].append(f"{qua['name']}： {qua['number']}")
        team_info[qua['account']]['证书截图'].append(os.path.join(ROOT_FOLDER, qua['file__path']))

        qua_id2account[qua['id']] = qua['account']

    # 工作经历
    query = Q(account__in=accounts)

    works = ExTeamWork.objects.filter(query).distinct()

    for work in works:
        if work.end:
            if work.end.isdigit():
                year = f"{work.begin}-{work.end}年，"
            else:
                year = f"{work.begin}年-{work.end}，"
        else:
            if work.begin:
                year = f"{work.begin}年，"
            else:
                year = ''

        if work.role:
            work_content = f"{year}作为{work.role}，{work.work}。"
        else:
            work_content = f"{year}{work.work}。"
        team_info[work.account]['主要工作经历'].append(work_content)

    # 以往参与项目情况
    query = Q(account__in=accounts)

    projects = ExTeamProject.objects.filter(query).distinct()

    for i, project in enumerate(projects, start=1):
        team_info[project.account]['以往参与项目情况'].append(f"{i}、{project.year}年，{project.projectContent}。")

    # 获取团队的社保缴纳证明
    # query = Q(bid=_id)
    # bidSocialInsurances = ExBidSocialInsurance.objects.filter(query).select_related('file').distinct()
    team_bidSocialInsurances = []

    # for obj in bidSocialInsurances:
    #     path = obj.file.path
    #     year = obj.year
    #     month = obj.month
    #     team_bidSocialInsurances.append([f"{year}{str(month).rjust(2, '0')}",
    #                                      f"{year}年{month}月社保缴纳证明",
    #                                      path])

    # 转为列表
    team_info = list(team_info.values())
    print(team_info)


    _type = 'team'

    # 文件存储位置
    save_folder = os.path.join(BIG_SAVE_FOLDER, _type)
    now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
    filename = f"团队生成_{now}.docx"
    save_path = os.path.join(save_folder, filename)
    if not os.path.isdir(save_folder):
        os.makedirs(save_folder)
    # print(save_path)

    # generate_team(team_info[:3], team_bidSocialInsurances, save_path)
    generate_team(team_info, team_bidSocialInsurances, save_path, bid_id, extra)

    return filename, save_path